package com.igoal.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.igoal.dto.PotentialFriendDTO;
import com.igoal.service.UserManagerExt;
import com.igoal.web.model.SearchResultModel;

@Controller
public class AjaxSearchController extends BaseAjaxController {
	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/ajax/secure/search.html")
	public String search(ModelMap modelMap, @ModelAttribute("search") SearchResultModel model, HttpServletRequest request){		
		model.setPrevPage(model.getPage()-1);
		model.setNextPage(-1);
		
		initRightPage(model, request);
		initLeftPage(model, request);
		initTopPage(model, request);
		
		if(Constants.SEARCH_FRIEND == model.getSearchType()){
			searchFriend(modelMap, model);
			return getViewPrefix() + "ajaxSearchFriendResult";
		}
		
		applyModel(modelMap, model);
		
		return "emptySearchResult";
	}
	
	public void searchFriend(ModelMap modelMap, SearchResultModel model){
		String username = getUserInSession();
		String keyword = model.getKeyword();
		int page = model.getPage();
		if(StringUtils.isNotBlank(keyword)){			
			keyword = keyword.replaceAll("\\*", "").replaceAll("\\.", "").replaceAll("_", "");
			keyword = keyword.trim();
			if(StringUtils.isNotBlank(keyword)){
				List<PotentialFriendDTO> result = userManagerExt.searchFriend(username, keyword, page);
				if(result != null){
					model.setResultOfFriendSearch(result);
					model.setHasNextPage(userManagerExt.checkSearchFriendResult(username, keyword, page+1));
					if(model.getHasNextPage()){
						model.setNextPage(page+1);
					}
				}
			}
		}
		
		applyModel(modelMap, model);
	}
}
